
function isEmpty(obj) {
  for (const prop in obj) {
    if (Object.hasOwn(obj, prop)) {
      return false;
    }
  }

  return true;
}

//function isMobile () {
//  let isMobile = false;
//  if((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
//      // console.log('移动端');
//      isMobile = true;
//  }
//  if (document.body.clientWidth < 800) {
//      isMobile = true;
//  }
//  return isMobile
//}

class PathMap {
  constructor(map_info, entrance_id) {
    this.map_id = map_info["id"]
    this.date = new Date(map_info["date"] * 1000)
    var utm = map_info["range"]
    var ll1 = UTMtoLL(utm[0].y, utm[0].x, utm[0].zone)
    var ll2 = UTMtoLL(utm[1].y, utm[1].x, utm[1].zone)
    this.range = [ll1, ll2]
    this.usage_count = map_info["usageCount"]
    this.back_build = map_info["backGroundBuild"]
    this.entrance_id = entrance_id
    this.has_map_files = true
    // console.log(map_info)
  }

  SetMapProperties = (files) => {
    this.files = files;
    this.has_map_files = true
  }

  FocusThis = () => {
    if (focus) {
      ResetFocus()
    }
    this.bbox.remove()
    this.RenderBbox("red")
    this.td_ele.style.backgroundColor = "red"
    focus = { entrance_id: this.entrance_id, map_id: this.map_id }
    this.td_ele.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" })
    utm_map.fitBounds(L.latLngBounds(this.range), { animate: false })
  }

  BboxClick(e) {
    // alert(e.target.options.map_id)
    index.Get(e.target.options.entrance_id).Get(e.target.options.map_id).FocusThis()
  }

  Reset = () => {
    this.bbox.remove()
    this.RenderBbox("grey")
    this.td_ele.style.backgroundColor = ""
  }

  RenderBbox = (color) => {
    this.bbox = L.rectangle(this.range, {
      color: color, weight: 1, fillOpacity: 0.1, map_id: this.map_id,
      entrance_id: this.entrance_id
    }).addTo(utm_map).on("click", this.BboxClick)
    var info = "<dl><dt>entrance</dt>"
      + "<dd>" + this.entrance_id + "</dd>"
      + "<dt>map_id</dt>"
      + "<dd>" + this.map_id + "</dd>"
    this.bbox.bindPopup(info);
    this.bbox.on('mouseover', function (e) {
      this.openPopup();
    });
    this.bbox.on('mouseout', function (e) {
      this.closePopup();
    });
  }

  MapIdClickCallback = (event) => { this.FocusThis() }

  JumpTo(url, id) {
    var on_new_window = window.open(url)
    on_new_window.onload = function () {
      console.log("opening window with : ", file_list[id])
      on_new_window.window.preload_maps = file_list[id]
      on_new_window.window.preload_id = id
      if(index_from_remote) {
        on_new_window.postMessage({ buffer: file_list[id] });
      }
      else {
        on_new_window.postMessage({ files: file_list[id] });
      }

    }
    let el = document.getElementById("jumppage");
    //el.style.visibility = "hidden"
  }

  JumpToMapPage = (event) => {
    console.log("eeee 2D 3D 跳转面板")
    if(isEmpty(file_list) || isEmpty(file_list[this.map_id])) {
      if(index_from_remote) {
        alert('donwloading remote file...')
        queryMapId(this.map_id)
      } else {
        alert('Map file for '+ this.map_id +'not found for this index directory')
      }
      return
    }

    //if(isMobile) {
    //  this.JumpTo(MAP_EDITOR_URL_3D, this.map_id)
    //  return
    //}
    let el = document.getElementById("jumppage");
    el.style.visibility = "visible"
    var old_2d = document.getElementById("map_2d")
    var new_2d = old_2d.cloneNode(true)
    old_2d.parentNode.replaceChild(new_2d,old_2d)
    new_2d.addEventListener("click",(e)=>{
      this.JumpTo(MAP_EDITOR_URL, this.map_id)
    })

    var old_3d = document.getElementById("map_3d")
    var new_3d = old_3d.cloneNode(true)
    old_3d.parentNode.replaceChild(new_3d,old_3d)
    new_3d.addEventListener("click",(e)=>{
      this.JumpTo(MAP_EDITOR_URL_3D, this.map_id)
    })
  }



  RenderOpenMapButton = (parent_ele) => {
    // 单个item中的控件
    var tr_open_map = document.createElement("button")
    tr_open_map.innerHTML = "Open Map"
    tr_open_map.id = this.map_id
    tr_open_map.addEventListener("click", this.JumpToMapPage)
    parent_ele.style = "white-space:nowrap;"
    parent_ele.appendChild(tr_open_map)
  }

  RenderTableContent = (parent_table) => {
    var tr_ele = document.createElement("tr")
    this.td_ele = document.createElement("td")
    var date_str = this.date.toLocaleString()
    this.td_ele.innerHTML = this.map_id + " (" + date_str + ")"
    this.td_ele.setAttribute("id", this.map_id)
    if (this.has_map_files) {
      this.RenderOpenMapButton(this.td_ele)
    }
    this.td_ele.addEventListener("click", this.MapIdClickCallback)
    tr_ele.appendChild(this.td_ele)
    parent_table.appendChild(tr_ele)
    this.RenderBbox()
  }
};

class LotMap {
  constructor(lot_info) {
    this.entrance_id = lot_info["id"];
    this.paths = new Map()
    var utm_entrance = lot_info["entrance"];
    this.entrance_ll = UTMtoLL(utm_entrance.y, utm_entrance.x, utm_entrance.zone)
    for (var map of lot_info["maps"]) {
      var range_check = map['range']
      if((range_check[0].x > 1e100 ||range_check[0].x < -1e100 )) {
        console.warn('BAD MAP : ' , map)
        continue
      }
      this.paths.set(map["id"], new PathMap(map, this.entrance_id))
    }
  }

  Get = (map_id) => { return this.paths.get(map_id) }

  RenderLotTable = (container) => {
    var entrance_table = document.createElement('table')
    container.appendChild(entrance_table)
    L.marker(this.entrance_ll).addTo(utm_entrance_map) // global utm_entrance_map
    var tr_entrance = document.createElement("tr")
    var td_entrance = document.createElement("td")
    //eeee 获取围栏信息
    console.log("eeee 围栏信息")
    td_entrance.innerHTML = "ID = " + this.entrance_id + " , LEN = " + Object.keys(this.paths).length
    tr_entrance.appendChild(td_entrance)
    entrance_table.appendChild(tr_entrance)
    this.paths.forEach(element => {
      element.RenderTableContent(entrance_table)
      utm_map.fitBounds(L.latLngBounds(element.range), { animate: false })
      container.appendChild(document.createElement("br"))
    })

  }
};

class Index {
  constructor(index_pb) {
    this.parking_lots = new Map()
    for (var parking_lot of index_pb.parkingLots) {
      this.parking_lots.set(parking_lot["id"], new LotMap(parking_lot))
    }
  }

  Get = (entrance_id) => { return this.parking_lots.get(entrance_id) }

  setFromRemote = (flag) => {
    this.from_remote = flag
  }


  RenderIndexTable = (container) => {
    this.parking_lots.forEach(element => {
      element.RenderLotTable(container)
    })
  }
};